#include "internal.h"
#include "CompassSensor.h"
#include "CompassSensor.tmh"

const PROPERTYKEY g_SupportedCompassProperties[] =
{
    SENSOR_PROPERTY_TYPE,
    SENSOR_PROPERTY_STATE,
    SENSOR_PROPERTY_CURRENT_REPORT_INTERVAL,
    SENSOR_PROPERTY_PERSISTENT_UNIQUE_ID,
    SENSOR_PROPERTY_FRIENDLY_NAME,
    SENSOR_PROPERTY_DESCRIPTION, 
    SENSOR_PROPERTY_CONNECTION_TYPE,
    WPD_FUNCTIONAL_OBJECT_CATEGORY,
};

const PROPERTYKEY g_SupportedCompassDataFields[] =
{
    SENSOR_DATA_TYPE_TIMESTAMP,
    SENSOR_DATA_TYPE_MAGNETIC_HEADING_X_DEGREES,
};

CompassSensor::CompassSensor(WpdObjectProperties* pWpdObjectProperties): 
	SensorBase(pWpdObjectProperties) 
{
	m_strSensorName		= SENSOR_COMPASS_FRIENDLY_NAME;
	m_strSensorId		= SENSOR_COMPASS_ID;
	m_gdSensorUniqueId	= SENSOR_COMPASS_GUID;
	m_gdSensorCategory	= SENSOR_CATEGORY_ORIENTATION;
	m_gdSensorType		= SENSOR_TYPE_COMPASS_1D;
}

VOID CompassSensor::AddPropertyKeys(
	IPortableDeviceKeyCollection* pKeys)
{
    if (pKeys != NULL)
    {
        for (DWORD dwIndex = 0; dwIndex < ARRAYSIZE(g_SupportedCompassProperties); dwIndex++)
        {
            pKeys->Add(g_SupportedCompassProperties[dwIndex] );
        }
    }
}

VOID CompassSensor::AddDataFieldKeys(
	IPortableDeviceKeyCollection* pKeys)
{
    if (pKeys != NULL)
    {
        for (DWORD dwIndex = 0; dwIndex < ARRAYSIZE(g_SupportedCompassDataFields); dwIndex++)
        {
            pKeys->Add(g_SupportedCompassDataFields[dwIndex] );
        }
    }
}

/// 
/// RetrieveHeading returns the heading in degrees from a 
/// 64-bit compass-sensor reading. The reading has the following
/// format: 113019 where the first byte is the identifier
/// the second and third bytes contain packet length and the 
/// remaining bytes contain the heading (19 degrees in this case). 
///
float RetrieveHeading(__int64 llVal)
{
    __int64 llTemp=0;
    float fTemp=0.0;

    llTemp = llVal - 113000;
    fTemp = (float)llTemp;
    return fTemp;
}

HRESULT CompassSensor::OnGetDataValues(
    PROPERTYKEY &Key,
    IPortableDeviceValues*         pValues)
{
    HRESULT hr			= S_OK;
	float	fHeading	= 0.0;

    // Set compass sensor data   
    if (IsEqualPropertyKey(Key, SENSOR_DATA_TYPE_MAGNETIC_HEADING_X_DEGREES))
    {
        fHeading = RetrieveHeading((__int64)m_llSensorReading);
        hr = pValues->SetFloatValue(SENSOR_DATA_TYPE_MAGNETIC_HEADING_X_DEGREES, fHeading);
    }
	return hr;
}